import React, { useState } from 'react';
import {getTest2} from "../../api/promsie"
export default function Processasync(): JSX.Element {
  const [show, setShow] = useState<string>('流程控制');
  // 1. 创建统一的实例
//   let p = Promise.resolve();
// function asyncProcess(asyncFn:(logo:number,time:number)=>Promise<any>):(logo:number,time:number)=>Promise<any>{
//   return function(logo,time){
//     p=p.then(()=>asyncFn(logo,time));
//     return p;
//   }
// }
  let p = Promise.resolve() as Promise<unknown>;

  function asyncProcess<T, U>(
    asyncFn: (...restOfArgs: T[]) => Promise<U>
  ): (...restOfArgs: T[]) => Promise<unknown | U> {
    return function (...restOfArgs: T[]) {
      p = p.then(() => asyncFn(...restOfArgs));
      return p;
    };
  }

  function getAsync(logo: number, time: number): Promise<any> {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        const result = { logo, data: 'success' };
        resolve(result);
        console.log({ logo, data: 'success' });
        setShow(JSON.stringify(result));
      }, time);
    });
  }
//断网重连
  function reduceRequest(Fun:(...args:any[])=>Promise<any>):(...args:any[])=>Promise<any>{
    return function(params,{Count=10, TimeInterval=1000}={}){

      return new Promise((resolve,reject)=>{
        function executePromise(timer:NodeJS.Timer):Promise<any>{
          //如果重连次数没有，那就不执行
          if(Count<=0){
            clearInterval(timer)
            return Promise.reject(new  Error('重连次数达到了'))

          }
          //2.  重连次数-1
          Count-=1
          //3 处理成功（链接成功）
          return Fun(params).then((res)=>{
            clearInterval(timer)
            resolve(res)

          }).catch((e)=>{
            throw new Error(e)
          })

        }
        let timer=setInterval(()=>{
          executePromise(timer)

        },TimeInterval)
        executePromise(timer)
      })
    }
  }
  function requestInit():void{
    reduceRequest(getTest2)(1,{Count:2,TimeInterval:1000}).then((res)=>{
      console.log(res);
      
    })
    
  }


  return (
    <>
      <h2>{show}</h2>

      <button
        onClick={() => {
          // 每一次的.then返回的都是一个Promise实例
          // p.then().then().then()
          // 通过Promise的链式调用 控制了异步流程
          // 思考题 : 怎么封装起来
          // p = p.then(() => {
          //   return getAsync(1, 200);
          // });
          asyncProcess(getAsync)(1, 200);

          // reduceRequest(GetAsync)(1,2000)

          // reduceRequest(异步请求)(请求参数,重连参数,重连次数,每次重连间隔时间)

          // 思考题 : 怎么封装起来 asyncProcess(getAsync)(参数) 控制异步流程
          // p = p.then(() => {
          asyncProcess<number, any>(getAsync)(1, 200);
          // });
        }}
      >
        异步请求1
      </button>
      <button
        onClick={() => {
          // p = p.then(() => {
          //   return getAsync(2, 1000);
          // });
          asyncProcess(getAsync)(2, 200);
          asyncProcess(getAsync)(2, 1000);
          // });
        }}
      >
        异步请求2
      </button>
      <button
        onClick={() => {
          // p = p.then(() => {
          //   return getAsync(3, 2000);
          // });
          asyncProcess(getAsync)(3, 200);
          asyncProcess(getAsync)(3, 2000);
        }}
      >
        异步请求3
      </button>
      <button
        onClick={() => {
        requestInit()
        }}
      >
        失败会重连
      </button>
    </>
  );
}
